var React = require('react');

var NewPost = React.createClass({
  getInitialState: function () {
    return {
      title: "",
      content: "",
      typeList: [],
      type: -1
    };
  },

  componentDidMount: function () {
    $.getJSON(baseUrl + "getTextTypeList", function (result, status) {
      console.log(result.data);
      if (this.isMounted()) {
        this.setState({
          typeList: result.data
        });
      }
    }.bind(this)).fail(function () {
      location.href = 'index.html';
    });
  },

  handleNewPost: function () {
    if ($.isBlank($('#new-post-title').val()) || $.isBlank($('#new-post-content').val()) || $.isBlank($('#type-select').val())) {
      console.log("empty, return");
      return;
    }

    var data = {
      title: $('#new-post-title').val(),
      text: $('#new-post-content').val(),
      text_type: parseInt($('#type-select').val())
    };

    console.log(data);
    $.post(baseUrl + "createNewText", data, function (result, status) {
      var post = result.data[0];
      location.href = 'post.html?id=' + post.id;
    }, 'json');
  },

  render: function () {
    return (
      <div>
        <div className="devide-title">
          <h1>写文章</h1>
        </div>
        <div className="new-post">
          <input id="new-post-title" placeholder="标题" type="text"/>
          <select id="type-select">
            {this.state.typeList.map(function (e) {
          return (
              <option key={e.id} value={e.id}>{e.name}</option>
          )
        })}
          </select>
          <br/>
          <textarea id="new-post-content" placeholder="文章内容"></textarea>
          <br/>
          <input id="new-post-button" onClick={this.handleNewPost} type="button" value="发表"/>
        </div>
      </div>
    );
  }
});

module.exports = NewPost;
